/**
 * 
 */
package com.cp16.tss.handler;

import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

import com.cp16.tss.bo.CustomerBO;
import com.cp16.tss.common.Constants;
import com.cp16.tss.dto.Address;
import com.cp16.tss.dto.Customer;
import com.cp16.tss.form.CustomerForm;
import com.cp16.tss.validation.CustomerValidation;

/**
 * @author ADMIN
 * 
 */
public class CustomerHandler {
	private CustomerBO customerBO = new CustomerBO();

	public boolean addNewCustomer(CustomerForm customerForm) {
		boolean flag = false;
		if (CustomerValidation.validateCustomerForm(customerForm)) {
			String customerId = customerForm.getTxtCustomerId().getText();
			try {
				if (customerBO.checkCustomerExist(Integer.valueOf(customerId))) {
					customerForm.getLblListForCustomer().setText("Customer ID is existed");
				} else {
					String customerName = customerForm.getTxtCustomerName().getText();
					String customerPhone = customerForm.getTxtPhone().getText();
					String customerStreet = customerForm.getTxtStreet().getText();
					String customerDistrict = customerForm.getTxtDistrict().getText();
					String customerCity = customerForm.getTxtCity().getText();
					// set address
					Address address = new Address();
					address.setStreetName(customerStreet);
					address.setDistrictName(customerDistrict);
					address.setCityName(customerCity);
					// set Customer
					Customer customer = new Customer();
					customer.setCustomerId(Integer.valueOf(customerId));
					customer.setCustomerName(customerName);
					if (!customerPhone.equals(Constants.BLANK)) {
						customer.setPhoneNumber(Integer.valueOf(customerPhone));
					}
					customer.setAddress(address);
					if (customerBO.addCustomer(customer)) {
						customerForm.getLblListForCustomer().setText("Add new customer successfull");
						displayTotalCustomer(customerForm);
						flag = true;
					}
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return flag;
	}

	public void editCustomer(CustomerForm customerForm) {
		int click = JOptionPane.showConfirmDialog(customerForm, 
				"are you sure edit this customer?", 
				"Edit a customer",
				JOptionPane.YES_NO_OPTION);
		if (click == JOptionPane.YES_OPTION) {
			if(!CustomerValidation.validateCustomerForm(customerForm)){
				return;
			} else {
				Customer customer = new Customer();
				Address address = new Address();
				address.setStreetName(customerForm.getTxtStreet().getText());
				address.setDistrictName(customerForm.getTxtDistrict().getText());
				address.setCityName(customerForm.getTxtCity().getText());
				customer.setCustomerId(Integer.valueOf(customerForm.getTxtCustomerId().getText()));
				customer.setCustomerName(customerForm.getTxtCustomerName().getText());
				customer.setAddress(address);
				if(!customerForm.getTxtPhone().getText().equals(Constants.BLANK)){
					customer.setPhoneNumber(Integer.valueOf(customerForm.getTxtPhone().getText()));
				}
				try {
					customerBO.updateCustomer(customer);
					JOptionPane.showMessageDialog(customerForm, "Edit successfull");
				} catch (Exception e) {
					JOptionPane.showMessageDialog(customerForm, "Edit fail");
					e.printStackTrace();
				}
			}
		}
		doClearAddNewCustomerForm(customerForm);
		enableButtonWhenEditCustomer(customerForm);
	}

	public void deleteCustomerFromTable(CustomerForm customerForm) {
		int selectColumnsNo = customerForm.getTblResultSearch().getSelectedRowCount();
		int[] rowColumnsSelected = customerForm.getTblResultSearch().getSelectedRows();
		if (selectColumnsNo > 0) {
			int click = JOptionPane.showConfirmDialog(customerForm,
					"Do you want to delete selected customer?",
					"Confirm delete customer", JOptionPane.YES_NO_OPTION);

			if (click == JOptionPane.YES_OPTION) {
				int rowIndex;
				int cellSelect;
				Customer customer;
				for (int i = 0; i < selectColumnsNo; i++) {
					rowIndex = customerForm.getTblResultSearch().convertRowIndexToModel(rowColumnsSelected[i]) - i;
					cellSelect = Integer.valueOf((String) customerForm.getTblResultSearch().getValueAt(rowIndex, 1));
					try {
						customer = customerBO.getCustomerById(cellSelect);
						customerBO.deleteCustomer(customer);
						((DefaultTableModel) customerForm.getTblResultSearch().getModel()).removeRow(rowIndex);
						customerForm.getTblResultSearch().repaint();
						displayTotalCustomer(customerForm);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}
	}

	public void doClearAddNewCustomerForm(CustomerForm customerForm) {
		customerForm.getLblListForCustomer().setText("Add new a customer");
		customerForm.getTxtCustomerId().setText(Constants.BLANK);
		customerForm.getTxtCustomerName().setText(Constants.BLANK);
		customerForm.getTxtCustomerId().setBackground(Color.WHITE);
		customerForm.getTxtCustomerName().setBackground(Color.WHITE);
		customerForm.getTxtPhone().setBackground(Color.WHITE);
		customerForm.getTxtStreet().setText(Constants.BLANK);
		customerForm.getTxtDistrict().setText(Constants.BLANK);
		customerForm.getTxtCity().setText(Constants.BLANK);
		customerForm.getTxtPhone().setText(Constants.BLANK);
		customerForm.getTxtCustomerId().setEditable(true);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void loadTable(CustomerForm customerForm) {
		DefaultTableModel defaultTableModel = (DefaultTableModel) customerForm.getTblResultSearch().getModel();
		int resultRow = customerForm.getTblResultSearch().getRowCount();
		for (int i = 0; i < resultRow; i++) {
			defaultTableModel.removeRow(0);
		}

		List<Customer> customerList = customerBO.getAllCustomer();
		if (customerList != null) {
			for (Customer customer : customerList) {
				Vector rowData = new Vector();
				rowData.add(customerList.indexOf(customer) + 1);
				rowData.add(String.valueOf(customer.getCustomerId()));
				rowData.add(customer.getCustomerName());
				if (customer.getAddress()!=null){
					rowData.add(customer.getAddress().getStreetName());
					rowData.add(customer.getAddress().getDistrictName());
					rowData.add(customer.getAddress().getCityName());
				}
				rowData.add(customer.getPhoneNumber());
				defaultTableModel.addRow(rowData);
			}
		}
		customerForm.getTblResultSearch().setModel(defaultTableModel);
		displayTotalCustomer(customerForm);
	}


	public void editCustomerForm(CustomerForm customerForm) {
		int selectColumnsNo = customerForm.getTblResultSearch().getSelectedRowCount();
		if (selectColumnsNo > 0) {
			disableButtonWhenEditCustomer(customerForm);
			int selectRow = customerForm.getTblResultSearch().getSelectedRow();
			int rowIndex = customerForm.getTblResultSearch().convertRowIndexToModel(selectRow);
			String ID = (String) customerForm.getTblResultSearch().getValueAt(rowIndex, 1);
			String name = (String) customerForm.getTblResultSearch().getValueAt(rowIndex, 2);
			String street = (String) customerForm.getTblResultSearch().getValueAt(rowIndex, 3);
			String district = (String) customerForm.getTblResultSearch().getValueAt(rowIndex, 4);
			String city = (String) customerForm.getTblResultSearch().getValueAt(rowIndex, 5);
			Integer phone = 0;
			if (!customerForm.getTblResultSearch().getValueAt(rowIndex, 6).equals(Constants.BLANK)) {
				phone = (Integer) customerForm.getTblResultSearch().getValueAt(rowIndex, 6);
			}
			customerForm.getLblListForCustomer().setText("Edit this customer");
			customerForm.getTxtCustomerId().setEditable(false);
			customerForm.getTxtCustomerId().setBackground(Color.WHITE);
			customerForm.getTxtCustomerId().setText(ID);
			customerForm.getTxtCustomerName().setText(name);
			customerForm.getTxtCustomerName().setBackground(Color.WHITE);
			customerForm.getTxtStreet().setText(street);
			customerForm.getTxtDistrict().setText(district);
			customerForm.getTxtCity().setText(city);
			customerForm.getTxtPhone().setText(String.valueOf(phone));
		}
	}
	
	public void disableButtonWhenEditCustomer(CustomerForm customerForm){
		customerForm.getBtnEdit().setEnabled(false);
		customerForm.getBtnDelete().setEnabled(false);
		customerForm.getBtnRefresh().setEnabled(false);
		customerForm.getBtnClose().setEnabled(false);
		
		customerForm.getBtnOk().setVisible(true);
		customerForm.getBtnCancel().setVisible(true);
		customerForm.getBtnAdd().setVisible(false);
		customerForm.getBtnClear().setVisible(false);
	}
	
	public void enableButtonWhenEditCustomer(CustomerForm customerForm){
		customerForm.getBtnEdit().setEnabled(true);
		customerForm.getBtnDelete().setEnabled(true);
		customerForm.getBtnRefresh().setEnabled(true);
		customerForm.getBtnClose().setEnabled(true);
		
		customerForm.getBtnOk().setVisible(false);
		customerForm.getBtnCancel().setVisible(false);
		customerForm.getBtnAdd().setVisible(true);
		customerForm.getBtnClear().setVisible(true);
	}

	public void searchCustomer(CustomerForm customerForm) {
		String customerIdSearch = customerForm.getTxtIdSearch().getText();
		String customerNameSearch = customerForm.getTxtNameSearch().getText();
		int customerFormListSize = customerForm.getTblResultSearch().getRowCount();
		List<Integer> indexList = new ArrayList<Integer>();
		for (int i = 0; i < customerFormListSize; i++) {
			String cusIdForm = (String) customerForm.getTblResultSearch().getValueAt(i, 1);
			String cusNameForm = (String) customerForm.getTblResultSearch().getValueAt(i, 2);
			if((!customerIdSearch.equals(Constants.BLANK) && !customerIdSearch.equals(cusIdForm)) 
					|| (!customerNameSearch.equals(Constants.BLANK) && !customerNameSearch.equalsIgnoreCase(cusNameForm))){
				indexList.add(i);
			}
		}
		for (int i = 0; i < indexList.size(); i++) {
			int rowIndex = customerForm.getTblResultSearch().convertRowIndexToModel(indexList.get(i)) - i;
			((DefaultTableModel) customerForm.getTblResultSearch().getModel()).removeRow(rowIndex);
			customerForm.getTblResultSearch().repaint();
		}
		customerForm.getTxtIdSearch().setText(Constants.BLANK);
		customerForm.getTxtNameSearch().setText(Constants.BLANK);
		displayTotalCustomer(customerForm);
	}
	
	public void displayTotalCustomer(CustomerForm customerForm){
		customerForm.getLblTotalCustomer().setText("Total: " + customerForm.getTblResultSearch().getRowCount() + " Customers");
	}
	

}
